<template>
  <div id="home">
    <!-- 添加返回上一级按钮 -->

    <div id="directory">
      <a-row :gutter="16" style="display: flex; justify-content: flex-end">
        <a-button type="primary" @click="goBack()">返回上一级</a-button>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="4" style="margin-bottom: 10px" v-for="item in menuItems" :key="item.key">
          <a-card :bordered="true">
            <span style="color: blue; cursor: pointer" @click="getRouteraa(item)">{{
              item.label
            }}</span>
          </a-card>
        </a-col>
      </a-row>
    </div>
    <div id="content">
      <router-view></router-view>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, ref, h, computed, watch } from 'vue'
import Directory from '../views/Directory.vue'
import { type MenuItems, menuItems } from '../layout/menu/menu'
import { useRouter, useRoute } from 'vue-router'

export default defineComponent({
  components: {
    Directory
  },
  setup() {
    const router = useRouter()
    const route = useRoute()

    const currentPathSegment = ref('')
    const segments = ref<string[]>([])
    const menuItemsRef = ref<MenuItems[]>([])

    onMounted(() => {
      updateFromRoute()
    })
    const goBack = () => {
      router.go(-1)
    }
    const updateFromRoute = () => {
      const pathSegments = route.path.split('/').filter(Boolean)
      segments.value = pathSegments
      currentPathSegment.value = pathSegments[pathSegments.length - 1] || ''
      menuItemsRef.value = findItemByKey(menuItems, currentPathSegment.value)
    }

    const getRouteraa = (item: MenuItems) => {
      router.push('/' + item.key)
    }

    const findItemByKey = (items: any[], key: string): any | undefined => {
      for (const item of items) {
        if (item.key === key) {
          return item.children
        } else {
          if (item.children) {
            const foundItem = findItemByKey(item.children, key)
            if (foundItem) {
              return foundItem
            }
          }
        }
      }
      return undefined
    }

    // 使用 watch 监听路由变化
    watch(route, () => {
      updateFromRoute()
    })

    return {
      getRouteraa,
      goBack,
      menuItems: menuItemsRef
    }
  }
})
</script>

<style scoped>
#directory a {
  text-decoration: none;
  color: #007bff;
}
#directory a:hover {
  text-decoration: underline;
}
</style>
